package com.siyoumi.sh.modules.gzhc365;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.siyoumi.sh.modules.common.IHandle;
import com.siyoumi.sh.modules.common.send_msg.TlSendMsg;
import com.siyoumi.sh.modules.gzhc365.entity.GzhcApiToken;
import com.siyoumi.sh.modules.gzhc365.entity.GzhcDoctor;
import com.siyoumi.sh.modules.gzhc365.entity.GzhcDoctorWorkToday;
import com.siyoumi.util.*;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//抢号 广中医
@Slf4j
public class GzhcHandle
        extends GzhcHandleBase
        implements IHandle {

    @SneakyThrows
    @Override
    public void run() {
        TlSendMsg.remove();

        List<GzhcApiToken> tokenArr = getArrToken();
        if (tokenArr.size() <= 0) {
            log.error("未配置GZHC_TOKEN");
            return;
        }
        log.info("BEGIN: {}", XDate.toDateTimeString());

        GzhcDoctor doctorTest = new GzhcDoctor();
        //{
        //    doctorTest.setHisId("2511"); //医院（广中医）
        //    doctorTest.setSubHisId("588"); //医院分部（广州机场路16号大院）
        //    doctorTest.setPlatformSource("3");
        //    doctorTest.setSubSource("1");
        //    doctorTest.setId("03678"); //王志刚
        //    //doctorTest.setTest(true);
        //    {
        //        GzhcDoctorWorkToday workToday = new GzhcDoctorWorkToday();
        //        workToday.setDeptNo("0005010");
        //        workToday.setDate(XDate.parse("2024-07-28"));
        //        doctorTest.setDoctorWork(workToday);
        //    }
        //}

        //{
        //    doctorTest.setHisId("2511"); //医院（广中医）
        //    doctorTest.setSubHisId("588"); //医院分部（广州机场路16号大院）
        //    doctorTest.setPlatformSource("3");
        //    doctorTest.setSubSource("1");
        //    doctorTest.setId("01090"); //王培源
        //    doctorTest.setTest(true);
        //}

        {
            doctorTest.setHisId("2511"); //医院（广中医）
            doctorTest.setSubHisId("588"); //医院分部（广州机场路16号大院）
            doctorTest.setPlatformSource("3");
            doctorTest.setSubSource("1");
            doctorTest.setId("73270"); //罗颂平
            {
                GzhcDoctorWorkToday workToday = new GzhcDoctorWorkToday();
                workToday.setDeptNo("0013000");
                workToday.setDate(XDate.parse("2024-09-25"));
                doctorTest.setDoctorWork(workToday);
            }
        }

        //{
        //    doctorTest.setHisId("2511"); //医院（广中医）
        //    doctorTest.setSubHisId("588"); //医院分部（广州机场路16号大院）
        //    doctorTest.setPlatformSource("3");
        //    doctorTest.setSubSource("1");
        //    doctorTest.setId("74060"); //周岱翰
        //    {
        //        GzhcDoctorWorkToday workToday = new GzhcDoctorWorkToday();
        //        workToday.setDeptNo("0012000");
        //        workToday.setDate(XDate.parse("2024-08-23"));
        //        doctorTest.setDoctorWork(workToday);
        //    }
        //}

        LocalDateTime startTime = XDate.parse("2024-08-24 19:59:59");

        GzhcApiToken apiToken = getArrToken().get(0);

        while (true) {
            Duration between = XDate.between(XDate.now(), startTime);
            long seconds = between.getSeconds();
            log.info("left seconds: {}", seconds);
            if (seconds <= 0) {
                logAndSet(TlSendMsg.get(), "**准备抢号** \n\n");
                break;
            }

            XApp.sleep(1);
        }

        play(apiToken, doctorTest);

        TlSendMsg.remove();
        log.info("END: {}", XDate.toDateTimeString());
    }

    private void play(GzhcApiToken apiToken, GzhcDoctor doctor) {
        List<GzhcDoctorWorkToday> listDoctorWork;

        GzhcDoctorWorkToday doctorWorkMax = null;
        if (doctor.getDoctorWork() == null) {
            while (true) {
                listDoctorWork = getDoctorWork(apiToken, doctor);
                if (listDoctorWork == null) {
                    //接口报错
                    //sendMsg(TlSendMsg.get().toString());
                    break;
                }
                if (listDoctorWork.size() <= 0) {
                    logAndSet(TlSendMsg.get(), "医生还没有放号，继续等待\n\n");
                } else {
                    //有号跳出
                    break;
                }

                //等1秒
                sleepAndLog(1);
            }

            if (listDoctorWork == null) {
                //接口报错
                sendMsg(TlSendMsg.get().toString());
                return;
            }

            for (GzhcDoctorWorkToday doctorWork : listDoctorWork) {
                logAndSet(TlSendMsg.get(), XStr.format("{0}-{3}:{1}/{2}\n\n", XDate.toDateString(doctorWork.getDate())
                                , doctorWork.getLeftNum().toString()
                                , doctorWork.getTotalNum().toString()
                                , doctorWork.getExtFields()
                        )
                );

                if (doctorWorkMax == null) {
                    doctorWorkMax = doctorWork;
                }

                if (doctorWorkMax.getLeftNum() < doctorWork.getLeftNum()) {
                    doctorWorkMax = doctorWork;
                }
            }

            logAndSet(TlSendMsg.get(), "**余量最多挂号** \n\n");
            logAndSet(TlSendMsg.get(), XStr.format("{0}-{3}:{1}/{2}\n\n", XDate.toDateString(doctorWorkMax.getDate())
                            , doctorWorkMax.getLeftNum().toString()
                            , doctorWorkMax.getTotalNum().toString()
                            , doctorWorkMax.getExtFields()
                    )
            );
        } else {
            doctorWorkMax = doctor.getDoctorWork();
            logAndSet(TlSendMsg.get(), XStr.format("**指定时间** {0}\n\n", XDate.toDateString(doctorWorkMax.getDate())));
        }

        qiang(apiToken, doctor, doctorWorkMax);

        sendMsg(TlSendMsg.get().toString());
    }


    //获取医生挂号记录
    private List<GzhcDoctorWorkToday> getDoctorWork(GzhcApiToken apiToken, GzhcDoctor doctor) {
        String url = "https://xcx.med.gzhc365.com/api/customize/getDoctorRegSourceWork?_route=h2511";

        Map<String, String> postData = new HashMap<>();
        postData.put("hisId", doctor.getHisId());
        postData.put("subHisId", doctor.getSubHisId());
        postData.put("platformId", doctor.getPlatformId());
        postData.put("platformSource", doctor.getPlatformSource());
        postData.put("subSource", doctor.getSubSource());
        postData.put("doctorCode", doctor.getId());
        postData.put("login_access_token", apiToken.getToken());

        XReturn r = forPostForm(url, getHeader(), postData);
        if (r.err()) {
            logAndSet(TlSendMsg.get(), "获取医生挂号记录失败：" + r.getErrMsg() + "\n\n");
            return null;
        }

        List<GzhcDoctorWorkToday> listData = new ArrayList<>();

        JSONArray data = (JSONArray) r.get("data");
        for (Object item : data) {
            JSONObject obj = (JSONObject) item;
            String date = obj.getString("date");

            JSONArray list = obj.getJSONArray("list");
            for (Object dateItem : list) {
                JSONObject objDate = (JSONObject) dateItem;
                GzhcDoctorWorkToday doctorWork = XJson.parseObject(objDate.toJSONString(), GzhcDoctorWorkToday.class);
                doctorWork.setDate(XDate.parse(date));

                if (doctorWork.getLeftNum() <= 0) {
                    //号没有库存，跳过
                    continue;
                }
                Integer timeFlag = objDate.getInteger("timeFlag");
                if (timeFlag == 1) {
                    //早上
                    doctorWork.setTimeType(0);
                } else if (timeFlag == 2) {
                    //下午
                    doctorWork.setTimeType(1);
                }


                listData.add(doctorWork);
            }
        }

        return listData;
    }
}
